/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useMemo, useRef, useState } from 'react';
import { message, Spin, Form, Row, Col } from 'antd';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormDateTimePicker,
  ProFormDependency,
  ProFormTextArea,
  ProFormRadio,
  ProFormSelect,
  ProFormUploadButton,
} from '@ant-design/pro-form';
import type { RuleObject } from 'antd/lib/form';
import type { StoreValue } from 'antd/lib/form/interface';
import { isTimeOutType, signType } from '../../../utils/ad.marketingSms';
import moment from 'moment';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { WinSize } from '@base/hooks/win';
import { createMarketBatchByExcel, updateMarketSmsList } from '@/services/ad/marketingSms/index';

interface KbAddSmsDrawerForm {
  id?: string;
  visible: boolean;
  actionRef: any;
  onCancel: () => void;
  winSize: WinSize | undefined;
}

const Index = ({ id, visible, actionRef, winSize, onCancel }: KbAddSmsDrawerForm) => {
  const formRef = useRef<ProFormInstance>();
  const [form] = Form.useForm();
  const contentValue = Form.useWatch('content', form);
  const sms_signValue = Form.useWatch('sms_sign', form);
  const [loading, setLoading] = useState<boolean>(false);

  const uploadValidator = (_: RuleObject, value: StoreValue) => {
    if (value && value.length > 0) {
      const { name } = value[0];
      if (!name.includes('xlsx')) {
        return Promise.reject(new Error('请选择xlsx文件'));
      }
      return Promise.resolve();
    } else {
      return Promise.reject(new Error('请选择Excel文件导入'));
    }
  };

  const onSubmit = async (values: any) => {
    if (loading) return;
    delete values.isTimeOut;
    const formData = new FormData();
    const { file = [], ...rest } = values;
    const params = rest;
    if (file[0]?.originFileObj) {
      params.file = file[0]?.originFileObj;
    }
    if (id) {
      params.id = id;
    }

    Object.keys(params).forEach((key) => {
      formData.append(key, params[key]);
    });
    setLoading(true);
    const api = id ? updateMarketSmsList : createMarketBatchByExcel;
    api(formData).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success(msg);
        onCancel();
        if (id) {
          actionRef.current?.reload();
        }
      } else {
        message.error(msg);
      }
      setLoading(false);
    });
  };

  const formatContentValue = useMemo(() => {
    return `${contentValue || ''}${signType[sms_signValue] || ''}`;
  }, [contentValue, sms_signValue]);

  const smsCount = useMemo(() => {
    const n = formatContentValue?.length || 0;
    if (n == 0) {
      return 0;
    } else if (n <= 70) {
      return 1;
    } else {
      return Math.ceil(n / 67);
    }
  }, [formatContentValue]);

  return (
    <ModalForm
      title='发送营销短信'
      formRef={formRef}
      form={form}
      width={winSize === 'xs' ? '100%' : 500}
      visible={visible}
      labelAlign='left'
      layout='horizontal'
      submitter={{
        searchConfig: {
          submitText: '发送',
        },
      }}
      labelCol={{
        span: 5,
      }}
      modalProps={{
        onCancel,
        destroyOnClose: true,
      }}
      onFinish={onSubmit}
      initialValues={{
        isTimeOut: '0',
        sms_sign: '微快递',
      }}
    >
      <Spin spinning={loading}>
        <ProForm.Item noStyle hidden={!!id}>
          <ProFormUploadButton
            max={1}
            accept='.xlsx'
            name='file'
            buttonProps={{ type: 'primary' }}
            title='Excel导入账号'
            rules={!id ? [{ validator: uploadValidator }] : []}
            extra={[
              <a key='warning'>
                excel表格信息规范:从第一行第一列按顺序输入正确的手机号，中间不要有空缺，其余地方不要有任何信息
              </a>,
            ]}
          />
          <ProFormText
            name='batch_number'
            label='批次号'
            placeholder='请输入批次号'
            rules={!id ? [{ required: true, message: '请输入批次号' }] : []}
            extra={[<a key='tips'>批次号格式：年月日+两位序列号，如：2023031401</a>]}
          />
        </ProForm.Item>
        <ProFormText
          name='subject'
          label='短信主题'
          placeholder='请输入短信主题'
          rules={[{ required: true, message: '请输入短信主题' }]}
        />
        <ProFormTextArea
          name='content'
          label='短信内容'
          placeholder='请输入短信内容'
          rules={[{ required: true, message: '请输入短信内容' }]}
          fieldProps={{
            maxLength: 1000,
          }}
        />
        <Row
          align={'middle'}
          justify={'space-between'}
          style={{ marginTop: -18, marginBottom: 15 }}
        >
          <Col offset={5}>{formatContentValue?.length || 0}/1000</Col>
          <Col>短信条数({smsCount})</Col>
        </Row>
        <ProFormRadio.Group
          label='发送时间'
          name='isTimeOut'
          rules={[{ required: true, message: '请选择发送时间' }]}
          valueEnum={isTimeOutType}
        />
        <ProFormDependency name={['isTimeOut']}>
          {({ isTimeOut }) => {
            return isTimeOut === '1' ? (
              <ProFormDateTimePicker
                name='send_time'
                label=' '
                colon={false}
                placeholder='请输入短信时间'
                rules={[{ required: true, message: '请输入短信时间' }]}
                fieldProps={{
                  style: { width: '100%' },
                  disabledDate: (data) => data && data < moment().subtract(10, 'days'),
                }}
              />
            ) : null;
          }}
        </ProFormDependency>
        <ProFormSelect
          name='sms_sign'
          label='选择签名'
          valueEnum={signType}
          placeholder='请输入短信签名'
        />
      </Spin>
    </ModalForm>
  );
};

export default Index;
